package cn.stylefeng.guns.modular.transport.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import cn.stylefeng.guns.modular.basic.entity.BasicLinePrice;
import cn.stylefeng.guns.modular.basic.model.result.BasicCarrierResult;
import cn.stylefeng.guns.modular.order.entity.OrderOutpreparePlatooncar;
import cn.stylefeng.guns.modular.order.entity.OrderTransport;
import cn.stylefeng.guns.modular.order.service.OrderOutpreparePlatooncarService;
import cn.stylefeng.guns.sys.modular.system.entity.Role;
import cn.stylefeng.guns.sys.modular.system.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.base.shiro.annotion.Permission;
import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.modular.basic.entity.BasicAddress;
import cn.stylefeng.guns.modular.basic.entity.BasicCarrier;
import cn.stylefeng.guns.modular.basic.entity.BasicDriver;
import cn.stylefeng.guns.modular.basic.entity.BasicLine;
import cn.stylefeng.guns.modular.basic.entity.BasicOperate;
import cn.stylefeng.guns.modular.basic.entity.BasicPrivatecar;
import cn.stylefeng.guns.modular.basic.model.params.BasicCarrierParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicDriverParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicLinePriceParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicLoadingQuotationParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicOilCardParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicPrivatecarParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicLinePriceResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicLoadingQuotationResult;
import cn.stylefeng.guns.modular.basic.service.BasicAddressService;
import cn.stylefeng.guns.modular.basic.service.BasicCarrierService;
import cn.stylefeng.guns.modular.basic.service.BasicCustomerService;
import cn.stylefeng.guns.modular.basic.service.BasicDriverService;
import cn.stylefeng.guns.modular.basic.service.BasicLinePriceService;
import cn.stylefeng.guns.modular.basic.service.BasicLineService;
import cn.stylefeng.guns.modular.basic.service.BasicLoadingQuotationService;
import cn.stylefeng.guns.modular.basic.service.BasicOilCardService;
import cn.stylefeng.guns.modular.basic.service.BasicOperateService;
import cn.stylefeng.guns.modular.basic.service.BasicPrivatecarService;
import cn.stylefeng.guns.modular.order.model.params.OrderTransportDetailedParam;
import cn.stylefeng.guns.modular.order.model.params.OrderTransportParam;
import cn.stylefeng.guns.modular.order.model.result.OrderTransportDetailedResult;
import cn.stylefeng.guns.modular.order.model.result.OrderTransportResult;
import cn.stylefeng.guns.modular.order.service.OrderTransportDetailedService;
import cn.stylefeng.guns.modular.order.service.OrderTransportService;
import cn.stylefeng.guns.modular.transport.entity.TDispatch;
import cn.stylefeng.guns.modular.transport.entity.TransportCost;
import cn.stylefeng.guns.modular.transport.entity.TransportDispatch;
import cn.stylefeng.guns.modular.transport.model.params.TDispatchParam;
import cn.stylefeng.guns.modular.transport.model.params.TransportCostParam;
import cn.stylefeng.guns.modular.transport.model.params.TransportDispatchParam;
import cn.stylefeng.guns.modular.transport.model.params.TransportMsgParam;
import cn.stylefeng.guns.modular.transport.model.params.TransportStevedoreSigninParam;
import cn.stylefeng.guns.modular.transport.model.result.TDispatchResult;
import cn.stylefeng.guns.modular.transport.model.result.TransportCostResult;
import cn.stylefeng.guns.modular.transport.model.result.TransportDispatchResult;
import cn.stylefeng.guns.modular.transport.model.result.TransportMsgResult;
import cn.stylefeng.guns.modular.transport.model.result.TransportStevedoreSigninResult;
import cn.stylefeng.guns.modular.transport.service.TDispatchService;
import cn.stylefeng.guns.modular.transport.service.TransportCostService;
import cn.stylefeng.guns.modular.transport.service.TransportDispatchService;
import cn.stylefeng.guns.modular.transport.service.TransportMsgService;
import cn.stylefeng.guns.modular.transport.service.TransportStevedoreSigninService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.FileInfoService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;

/**
 * web调度
 * 控制器
 */
@Controller
@RequestMapping("/orderTransportDispatch")
public class dispatchController extends BaseController {

    private String PREFIX = "/transport/dispatch";

    @Autowired
    private BasicOperateService basicOperateService;
    @Autowired
    private BasicCustomerService basicCustomerService;
    @Autowired
    private OrderTransportService orderTransportService;
    @Autowired
    private OrderTransportDetailedService orderTransportDetailedService;
    @Autowired
    private BasicPrivatecarService basicPrivatecarService;
    @Autowired
    private TransportDispatchService transportDispatchService;
    @Autowired
    private TDispatchService tDispatchService;
    @Autowired
    private OrderOutpreparePlatooncarService orderOutpreparePlatooncarService;
    @Autowired
    private TransportCostService transportCostService;
    @Autowired
    private UserService userService;
    @Autowired
    private BasicAddressService basicAddressService;
    private Lock lock = new ReentrantLock();
    private Lock lock2 = new ReentrantLock();

    /**
     * to修改位置页面
     */
    @RequestMapping("toGaidizhi")
    public String toGaidizhi(Model model, Long setLocationId) {
        BasicAddress basicAddress = basicAddressService.getById(setLocationId);
        model.addAttribute("set_longitude", basicAddress.getLongitude());
        model.addAttribute("set_latitude", basicAddress.getLatitude());
        return PREFIX + "/gaidizhi.html";
    }

    /**
     * to调度页面
     */
    @RequestMapping("")
    public String index(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(deptId, deliverId, user.getOperateId()));
        model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId, deliverId, user.getOperateId()));

        BasicCarrierParam basicCarrierParam = new BasicCarrierParam();
        basicCarrierParam.setDeliverId(deliverId);
        model.addAttribute("carrierlist", basicCarrierService.findListBySpec(basicCarrierParam, user.getOperateId()));
        return PREFIX + "/dispatch.html";
    }

    /**
     * 查询待调订单
     */
    @ResponseBody
    @RequestMapping("/findDispatchPageBySpec")
    public LayuiPageInfo findDispatchPageBySpec(OrderTransportParam orderTransportParam, String condition, String startTime, String endTime, String startTime2, String endTime2) {
        User user = userService.getcurrentUser();
        orderTransportParam.setDeliverId(user.getDeliverId());
        orderTransportParam.setDeptId(user.getDeptId());
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            orderTransportParam.setUndertime("'" + startTime + "' and '" + endTime + "'");
        }
        if (ToolUtil.isNotEmpty(startTime2) && ToolUtil.isNotEmpty(endTime2)) {
            orderTransportParam.setSetMentiontime("'" + startTime2 + "' and '" + endTime2 + "'");
        } else if (startTime2 == null && endTime2 == null) {
            startTime2 = DateUtil.getMonth() + "-01";
            endTime2 = DateUtil.getDate();
            orderTransportParam.setSetMentiontime("'" + startTime2 + "' and '" + endTime2 + "'");
        }

        String roleId = user.getRoleId();
        if (ToolUtil.isNotEmpty(roleId)) {
            for (String rId : roleId.split(",")) {
                Role byId = roleService.getById(rId);
                if (byId != null && byId.getName().contains("Carrier")) {
                    BasicCarrierParam param = new BasicCarrierParam();
                    param.setUserId(user.getUserId());
                    BasicCarrierResult bySpec = basicCarrierService.findBySpec(param, user.getOperateId());
                    if (bySpec != null) {
                        orderTransportParam.setCarrierId(bySpec.getId());
                    } else {
                        orderTransportParam.setCarrierId(-1);
                    }
                }
            }
        }


        return this.orderTransportService.findDispatchPageBySpec(orderTransportParam, condition, user.getOperateId());
    }

    /**
     * to拆明细页面
     */
    @RequestMapping("tochai")
    public String tochai(Model model) {
        return PREFIX + "/dispatchDetailed.html";
    }

    /**
     * 查询待调订单明细
     */
    @ResponseBody
    @RequestMapping("/findListBySpecWeiPei")
    public LayuiPageInfo findListBySpecWeiPei(OrderTransportDetailedParam OrderTransportDetailedParam) {
        List<OrderTransportDetailedResult> list = this.orderTransportDetailedService.findListBySpecWeiPei(OrderTransportDetailedParam);
        LayuiPageInfo layuiPageInfo = new LayuiPageInfo();
        layuiPageInfo.setData(list);
        layuiPageInfo.setCount(list.size());
        return layuiPageInfo;
    }

    /**
     * to选择车辆
     */
    @RequestMapping("/toCar")
    public String toCar(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择分公司
        model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId, deliverId, user.getOperateId()));
        return PREFIX + "/choiceCar.html";
    }

    /**
     * 查询车辆
     * 空闲、已调、在途
     */
    @ResponseBody
    @RequestMapping("/privatecarlist")
    public LayuiPageInfo privatecarlist(BasicPrivatecarParam basicPrivatecarParam, String condition) {
        User user = userService.getcurrentUser();
        basicPrivatecarParam.setDeliverId(user.getDeliverId());
        String roleId = user.getRoleId();
        if (ToolUtil.isEmpty(condition) && ToolUtil.isNotEmpty(roleId)) {
            for (String rId : roleId.split(",")) {
                Role byId = roleService.getById(rId);
                if (byId != null && byId.getName().contains("Carrier")) {
                    BasicCarrierParam param = new BasicCarrierParam();
                    param.setUserId(user.getUserId());
                    BasicCarrierResult bySpec = basicCarrierService.findBySpec(param, user.getOperateId());
                    if (bySpec != null) {
                        basicPrivatecarParam.setPrivatecarFleetId(bySpec.getId());
                    } else {
                        basicPrivatecarParam.setPrivatecarFleetId(-1);
                    }
                }
            }
        }

        return this.basicPrivatecarService.findPageBySpec(basicPrivatecarParam, condition, null, null, user.getOperateId());
    }

    /**
     * 选择车辆
     */
    @RequestMapping("/batchassign")
    @ResponseBody
    public ResponseData batchassign(Long[] gids, String[] bids, String[] nums, String[] orders, String[] arrorders, Long carId) {
        List<OrderTransportDetailedParam> _list2 = new ArrayList<OrderTransportDetailedParam>();
        for (int i = 0; i < orders.length; i++) {
            OrderTransportDetailedParam o = new OrderTransportDetailedParam();
            try {
                o.setTransportNumber(orders[i]);
                if (bids.length > 0) {
                    String batchnumber = bids[i];
                    if (batchnumber != null && batchnumber != "") {
                        batchnumber = batchnumber.replace("& #40;", "(");
                        batchnumber = batchnumber.replace("& #41;", ")");
                    }
                    o.setBatchnumber(batchnumber);
                }
                o.setNum(nums[i]);
                o.setGoodId(gids[i]);
                _list2.add(o);
            } catch (Exception e) {
                return ResponseData.error("Data Error");
            }
        }
        for (int i = 0; i < arrorders.length; i++) {
            OrderTransportDetailedParam o = new OrderTransportDetailedParam();
            try {
                o.setTransportNumber(arrorders[i]);
                _list2.add(o);
            } catch (Exception e) {
                return ResponseData.error("Data Error");
            }
        }
        ResponseData data = new ResponseData();
        User user = userService.getcurrentUser();

        lock.lock();//获取锁
        try {
            data = transportDispatchService.batchassign_web(_list2, carId, user);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return data;
    }

    /**
     * to追加明细  选择车 页面
     */
    @RequestMapping("/toYunshuCar")
    public String toYunshuCar() {
        return PREFIX + "/yunshuCar.html";
    }

    /**
     * 追加明细  确定
     */
    @RequestMapping("/batchassignDispatchNumber")
    @ResponseBody
    public ResponseData batchassignDispatchNumber(Long[] gids, String[] bids, String[] nums, String[] orders, String[] arrorders, String dispatchNumber) {
        List<OrderTransportDetailedParam> _list2 = new ArrayList<OrderTransportDetailedParam>();
        for (int i = 0; i < orders.length; i++) {
            OrderTransportDetailedParam o = new OrderTransportDetailedParam();
            try {
                o.setTransportNumber(orders[i]);
                if (bids.length > 0) {
                    String batchnumber = bids[i];
                    if (batchnumber != null && batchnumber != "") {
                        batchnumber = batchnumber.replace("& #40;", "(");
                        batchnumber = batchnumber.replace("& #41;", ")");
                    }
                    o.setBatchnumber(batchnumber);
                }
                o.setNum(nums[i]);
                o.setGoodId(gids[i]);
                _list2.add(o);
            } catch (Exception e) {
                return ResponseData.error("Data Error");
            }
        }
        for (int i = 0; i < arrorders.length; i++) {
            OrderTransportDetailedParam o = new OrderTransportDetailedParam();
            try {
                o.setTransportNumber(arrorders[i]);
                _list2.add(o);
            } catch (Exception e) {
                return ResponseData.error("Data Error");
            }
        }
        ResponseData data = new ResponseData();
        User user = userService.getcurrentUser();
        lock2.lock();//获取锁
        try {
            data = transportDispatchService.batchassignNewDispatchNumber(_list2, dispatchNumber, data, user);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock2.unlock();//释放锁
        }
        return data;
    }

    /**
     * 查询 已配置车辆
     */
    @ResponseBody
    @RequestMapping("/findCarListBySpecToo")
    public LayuiPageInfo findCarListBySpecToo(TransportDispatchParam transportDispatchParam, String tstate) {
        User user = userService.getcurrentUser();
        transportDispatchParam.setDeliverId(user.getDeliverId());
        transportDispatchParam.setDeptId(user.getDeptId());
        String token = "Wait";
        String dispatch = "";
        if (ToolUtil.isNotEmpty(tstate)) {
            token = "";
            dispatch = "daidingjia";
        }

        String roleId = user.getRoleId();
        if (ToolUtil.isNotEmpty(roleId)) {
            for (String rId : roleId.split(",")) {
                Role byId = roleService.getById(rId);
                if (byId != null && byId.getName().contains("Carrier")) {
                    BasicCarrierParam param = new BasicCarrierParam();
                    param.setUserId(user.getUserId());
                    BasicCarrierResult bySpec = basicCarrierService.findBySpec(param, user.getOperateId());
                    if (bySpec != null) {
                        transportDispatchParam.setCarrierId(Long.valueOf(bySpec.getId()));
                    } else {
                        transportDispatchParam.setCarrierId(-1L);
                    }
                }
            }
        }

        List<TransportDispatchResult> list = this.transportDispatchService.findCarListBySpecToo(transportDispatchParam, null, null, token, null, dispatch, user.getOperateId());
        LayuiPageInfo layuiPageInfo = new LayuiPageInfo();
        layuiPageInfo.setData(list);
        layuiPageInfo.setCount(list.size());
        return layuiPageInfo;
    }

    /**
     * 追加明细
     * 查询已完成配置车辆
     */
    @ResponseBody
    @RequestMapping("/findCarListBySpecTooZhuijia")
    public LayuiPageInfo findCarListBySpecTooZhuijia(TransportDispatchParam transportDispatchParam, String tstate) {
        User user = userService.getcurrentUser();
        transportDispatchParam.setDeliverId(user.getDeliverId());
        transportDispatchParam.setDeptId(user.getDeptId());
        String token = "";
        String dispatch = "zhuijia";
        List<TransportDispatchResult> list = this.transportDispatchService.findCarListBySpecToo(transportDispatchParam, null, null, token, null, dispatch, user.getOperateId());
        LayuiPageInfo layuiPageInfo = new LayuiPageInfo();
        layuiPageInfo.setData(list);
        layuiPageInfo.setCount(list.size());
        return layuiPageInfo;
    }

    /**
     * 完成配置
     */
    @RequestMapping("/startCarGoods")
    @ResponseBody
    public ResponseData startCarGoods(TransportDispatchParam transportDispatchParam) {
        return transportDispatchService.startCarGoods(transportDispatchParam);
    }

    /**
     * 移除配置中 车辆
     */
    @RequestMapping("/removeCarBySpec")
    @ResponseBody
    public ResponseData removeCarBySpec(String carnumbger) {
        ResponseData data = new ResponseData();
        User user = userService.getcurrentUser();
        return this.transportDispatchService.removeCarBySpecNewWeb(carnumbger, data, user);
    }

    /**
     * 移除配置中 商品
     */
    @RequestMapping("/removeGoods")
    @ResponseBody
    public ResponseData removeGoods(String carnumbger, String transportNumber, Long goodsId) {
        ResponseData data = new ResponseData();
        User user = userService.getcurrentUser();
        return this.transportDispatchService.removeGoodsWeb(transportNumber, goodsId, carnumbger, data, user);
    }

    /**
     * 修改配置中 商品
     */
    @RequestMapping("/editGoods")
    @ResponseBody
    public ResponseData editGoods(TransportDispatchParam transportDispatchParam) {
        ResponseData data = new ResponseData();
        return this.transportDispatchService.editGoodsWeb(transportDispatchParam, data);
    }

    /**
     * to编辑配置中 明细
     */
    @RequestMapping("/tocheck")
    public String tocheck() {
        return PREFIX + "/check.html";
    }

    /**
     * 查询配置中 明细
     */
    @ResponseBody
    @RequestMapping("/listOrder")
    public LayuiPageInfo listOrder(TransportDispatchParam transportDispatchParam) {
        User user = userService.getcurrentUser();
        transportDispatchParam.setDeptId(user.getDeptId());
        String token = "Wait";
        transportDispatchParam.setDispatchNumber("yichu");
        List<TransportDispatchResult> list = this.transportDispatchService.findgoodslistBySpecWeb(transportDispatchParam, token, user.getOperateId());
        LayuiPageInfo layuiPageInfo = new LayuiPageInfo();
        layuiPageInfo.setData(list);
        layuiPageInfo.setCount(list.size());
        return layuiPageInfo;
    }

    /**
     * to查询配置中 明细
     */
    @RequestMapping("/tochecktoo")
    public String tochecktoo() {
        return PREFIX + "/checktoo.html";
    }

    /**
     * 撤销派车单
     */
    @RequestMapping("/removeDispatchNumberBySpec")
    @ResponseBody
    public ResponseData removeDispatchNumberBySpec(String dispatchNumber) {
        ResponseData data = new ResponseData();
        User user = userService.getcurrentUser();
        return this.transportDispatchService.removeDispatchNumberBySpec(dispatchNumber, data, user);
    }

    @Autowired
    private BasicOilCardService basicOilCardService;

    /**
     * to确认金额
     */
    @RequestMapping("/toeditmoney")
    public String toeditmoney(Model model) {
        User user = userService.getcurrentUser();
        //查询可选择油卡
        BasicOilCardParam basicOilCardParam = new BasicOilCardParam();
        basicOilCardParam.setDeptId(user.getDeptId());
        model.addAttribute("basicOilCardlist", basicOilCardService.findListBySpec(basicOilCardParam, user.getOperateId()));
        return PREFIX + "/editmoney.html";
    }

    /**
     * to调整费用
     */
    @Permission
    @RequestMapping("/toeditcost")
    public String toeditcost(Model model) {
        return PREFIX + "/editcost.html";
    }

    /**
     * 查看运输单
     */
    @RequestMapping("/detailBydispatchNumber")
    @ResponseBody
    public ResponseData detailBydispatchNumber(TDispatchParam tDispatchParam) {
        TDispatchResult detail = this.tDispatchService.findBySpec(tDispatchParam, null);
        return ResponseData.success(detail);
    }

    @Autowired
    private BasicLoadingQuotationService basicLoadingQuotationService;

    @Autowired
    private BasicLinePriceService basicLinePriceService;

    /**
     * 计算费用
     */
    @RequestMapping("/countCost2")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public ResponseData countCost2(String dispatchNumber, String loadingType, String mileageTraveled) {  //调度单号  装车方
        User user = userService.getcurrentUser(); //获取用户
        BigDecimal as = new BigDecimal("0");
        BigDecimal loadingMoney = new BigDecimal("0");  //创建2个计量对象赋值为0
        TDispatchParam tDispatchParam = new TDispatchParam();
        tDispatchParam.setDispatchNumber(dispatchNumber); //将调度单号填入
        TDispatchResult detail = this.tDispatchService.findBySpec(tDispatchParam, null); //根据调度单号查询信息
//		if (ToolUtil.isNotEmpty(loadingType)) { //如果装车方不为空
//			if (loadingType.equals("自装")) {//查询自装装车费
//				BasicLoadingQuotationParam loadingQuotationParam = new BasicLoadingQuotationParam();  //创建装车表对象
//				loadingQuotationParam.setOperateId(detail.getOperateId()); //填入传入调度单号项目id
//				BasicLoadingQuotationResult basicLoadingQuotationResult = basicLoadingQuotationService.findBySpec(loadingQuotationParam);
//				if (basicLoadingQuotationResult != null) {  //如果对象不为空
//					if (ToolUtil.isNotEmpty(basicLoadingQuotationResult.getPriceMode())) {  //如果计价方式不为空
//						if (basicLoadingQuotationResult.getPriceMode().equals("元/车")) { //如果计价方式 为此
//							if (ToolUtil.isNotEmpty(basicLoadingQuotationResult.getPrice())) { //计价标准
//								BigDecimal price = new BigDecimal(basicLoadingQuotationResult.getPrice()); //将计价标准赋值
//								if (price.compareTo(as) == 1) { // 如果计价标准大于0
//									loadingMoney = price;  // 让其等于0
//								}
//							}
//						}
//					}
//				}
//			}
//		}

        boolean eachOrderCost = false;//是否计算每单成本
        if (detail.getOperateId() != null) {
            BasicOperate basicOperate = basicOperateService.getById(detail.getOperateId());
            if (ToolUtil.isNotEmpty(basicOperate.getEachOrderCost())) {
                if (basicOperate.getEachOrderCost().equals("Yes")) {
                    eachOrderCost = true;
                }
            }
        }

        List<TransportDispatchResult> dlist = new ArrayList<TransportDispatchResult>();//配置明细
        TransportDispatchParam transportDispatchParam = new TransportDispatchParam();
        transportDispatchParam.setDispatchNumber(detail.getDispatchNumber());
        transportDispatchParam.setCarId(detail.getCarId());
        transportDispatchParam.setDeptId(user.getDeptId());
        List<TransportDispatchResult> llist = null;
        //齐河好想来 项目编号 39
        if (detail.getOperateId() == 39L) {
            llist = transportDispatchService.findLineListBySpecNew(transportDispatchParam, null, detail.getOperateId());//线路配置
        } else {
            llist = transportDispatchService.findLineListBySpec(transportDispatchParam, null, detail.getOperateId());//线路配置
        }

        if (eachOrderCost) {
            //齐河好想来 项目编号 39
            if (detail.getOperateId() == 39L) {
                dlist = transportDispatchService.findOrderListBySpecNew(transportDispatchParam, null, detail.getOperateId());//订单配置
            } else {
                dlist = transportDispatchService.findOrderListBySpec(transportDispatchParam, null, detail.getOperateId());//订单配置
            }
        } else {
            dlist = llist;
        }

        List<TransportCost> costlist = new ArrayList<TransportCost>();
        BigDecimal totalConsultMoney = BigDecimal.ZERO; // 声明一个总价钱变量，初始值为0

        boolean sfyc = false;
        for (TransportDispatchResult r : dlist) {
            if (r.getLineId() == null) { //如果线路为空
                return ResponseData.error(r.getGetUnit() + "Route not assigned");
            }
            BasicLine basicLine = basicLineService.getById(r.getLineId()); //获取线路id
            if (basicLine == null) {
                return ResponseData.error(r.getLineName() + "Route does not exist");
            }
            if (!basicLine.getStatus().equals("1")) {  //如果线路被禁用
                return ResponseData.error(basicLine.getLineName() + "Route has been disabled");
            }
            BasicLinePriceParam basicLinePriceParam = new BasicLinePriceParam();
            basicLinePriceParam.setCarrierId(detail.getCarrierId());
            basicLinePriceParam.setLineId(r.getLineId());
            List<BasicLinePriceResult> basicLinePricelist = basicLinePriceService.getlineprice(basicLinePriceParam);//查询线路报价的方法
            if (basicLinePricelist.size() == 0) {
                basicLinePriceParam.setCarrierId(null);
                basicLinePricelist = basicLinePriceService.getlineprice(basicLinePriceParam);
            }
            if (basicLinePricelist.size() == 0) {//如果没有报价并且计算每单运费，就添加一条空费用明细
                if (eachOrderCost) {
                    TransportCost addCost = new TransportCost();
                    addCost.setDispatchNumber(dispatchNumber);
                    addCost.setDeptId(detail.getDeptId());
                    addCost.setDeliverId(detail.getDeliverId());
                    addCost.setLineId(r.getLineId());
                    addCost.setLineName(r.getLineName());
                    addCost.setPriceName("Freight");
                    addCost.setNums(r.getTooDeployVolume());
                    addCost.setV2("0");
                    addCost.setMoney("0");
                    addCost.setV1(r.getTransportNumber());
                    costlist.add(addCost);
                    continue;
                }
            }
            if (llist.size() > 1 && basicLinePricelist.size() > 1) {
                sfyc = true;
            }
            for (BasicLinePriceResult r2 : basicLinePricelist) {
                TransportCost addCost = new TransportCost();
                addCost.setDispatchNumber(dispatchNumber);
                addCost.setDeptId(detail.getDeptId());
                addCost.setDeliverId(detail.getDeliverId());
                addCost.setLineId(r.getLineId());
                addCost.setLineName(r.getLineName());
                addCost.setPriceName("Freight");
                addCost.setNums(r.getTooDeployVolume());
                addCost.setV2("0");
                addCost.setMoney("0");
                if (eachOrderCost) {
                    addCost.setV1(r.getTransportNumber());
                }

                BigDecimal b2 = BigDecimal.ZERO;
                if (ToolUtil.isNotEmpty(r2.getPrice())) {
                    b2 = new BigDecimal(r2.getPrice());  //获取计价标准
                }

                BigDecimal volume = BigDecimal.ZERO;
                if (ToolUtil.isNotEmpty(r.getTooDeployVolume())) {
                    volume = new BigDecimal(r.getTooDeployVolume());  //获取体积
                }

                BigDecimal num = BigDecimal.ZERO;
                if (ToolUtil.isNotEmpty(r.getTooDeployNum())) {
                    num = new BigDecimal(r.getTooDeployNum()); //获取数量
                }

                BigDecimal licheng = BigDecimal.ZERO;
                if (ToolUtil.isNotEmpty(mileageTraveled)) {
                    licheng = new BigDecimal(mileageTraveled); //获取公里数
                }

                BigDecimal csxx = BigDecimal.ZERO;
                if (ToolUtil.isNotEmpty(r2.getPriceCsxx())) {
                    csxx = new BigDecimal(r2.getPriceCsxx()); //获取参数下限
                }

                BigDecimal cssx = BigDecimal.ZERO;
                if (ToolUtil.isNotEmpty(r2.getPriceCssx())) {
                    cssx = new BigDecimal(r2.getPriceCssx()); //获取参数上限
                }

                BigDecimal priceQb = BigDecimal.ZERO;
                if (ToolUtil.isNotEmpty(r2.getPriceQb())) {
                    priceQb = new BigDecimal(r2.getPriceQb()); //获取起步价
                }

                BigDecimal priceQbds = BigDecimal.ZERO;
                if (ToolUtil.isNotEmpty(r2.getPriceQbds())) {
                    priceQbds = new BigDecimal(r2.getPriceQbds()); //获取起步点数
                }

                BigDecimal prceQbcd = BigDecimal.ZERO;
                if (ToolUtil.isNotEmpty(r2.getPrceQbcd())) {
                    prceQbcd = new BigDecimal(r2.getPrceQbcd()); //获取超点费用
                }

                boolean chexingflag = true;//判断报价车型是否一直
                if (ToolUtil.isNotEmpty(r2.getCarType())) {
                    if (ToolUtil.isNotEmpty(detail.getChexing())) {
                        if (!r2.getCarType().equals(detail.getChexing())) {
                            chexingflag = false;
                        }
                    }
                }
                if (chexingflag) {
                    if (ToolUtil.isEmpty(r2.getPriceType()) || r2.getPriceType().equals("Fixed")) {
                        if (r2.getPriceMode().equals("CNY/m³")) {
                            BigDecimal b2mulvolume = volume.multiply(b2).setScale(3, BigDecimal.ROUND_HALF_DOWN);
                            totalConsultMoney = totalConsultMoney.add(b2mulvolume);

                            addCost.setPriceMode(r2.getPriceMode());
                            addCost.setPrice(b2 + "");
                            addCost.setNums(volume + "");
                            addCost.setMoney(b2mulvolume + "");
                        }
                        if (r2.getPriceMode().equals("CNY/Unit")) {
                            BigDecimal b2num = num.multiply(b2).setScale(3, BigDecimal.ROUND_HALF_DOWN);
                            totalConsultMoney = totalConsultMoney.add(b2num);

                            addCost.setPriceMode(r2.getPriceMode());
                            addCost.setPrice(b2 + "");
                            addCost.setNums(num + "");
                            addCost.setMoney(b2num + "");
                        }
                        if (r2.getPriceMode().equals("CNY/Vehicle")) {
                            if (sfyc) {
                                totalConsultMoney = BigDecimal.ZERO;
                            } else {
                                totalConsultMoney = totalConsultMoney.add(b2);
                            }

                            addCost.setPriceMode(r2.getPriceMode());
                            addCost.setPrice(b2 + "");
                            addCost.setNums("1");
                            addCost.setMoney(b2 + "");
                        }
                        if (r2.getPriceMode().equals("CNY/Km")) {
                            if (licheng.compareTo(as) == 1) {
                                BigDecimal b2licheng = licheng.multiply(b2).setScale(3, BigDecimal.ROUND_HALF_DOWN);
                                if (sfyc) {
                                    totalConsultMoney = BigDecimal.ZERO;
                                } else {
                                    totalConsultMoney = totalConsultMoney.add(b2licheng);
                                }

                                addCost.setPriceMode(r2.getPriceMode());
                                addCost.setPrice(b2 + "");
                                addCost.setNums(licheng + "");
                                addCost.setMoney(b2licheng + "");
                            }
                        }
                        if (r2.getPriceMode().equals("CNY/Point")) {
                            addCost.setPriceMode(r2.getPriceMode());
                            addCost.setPrice(priceQb + "");
                            addCost.setV3(priceQbds + "");
                            addCost.setV4(prceQbcd + "");
                            BigDecimal money = priceQb;

                            if (sfyc) {
                                totalConsultMoney = BigDecimal.ZERO;
                            } else {
                                totalConsultMoney = totalConsultMoney.add(priceQb);
                            }

                            // 计算是否超点
                            if (priceQbds.compareTo(as) == 1 && prceQbcd.compareTo(as) == 1) {
                                TransportDispatchParam countppp = new TransportDispatchParam();
                                countppp.setDispatchNumber(detail.getDispatchNumber());
                                countppp.setLineId(r.getLineId());
                                Integer countgg = transportDispatchService.countGetUnit(countppp);//合计该线路下  门店数
                                if (countgg != null && countgg > 0) {
                                    addCost.setNums(countgg + "");
                                    BigDecimal bigcountgg = new BigDecimal(countgg);
                                    if (bigcountgg.compareTo(priceQbds) == 1) {//如果门店数 大于 起步点数
                                        BigDecimal countsubqbds = bigcountgg.subtract(priceQbds);
                                        BigDecimal cmcd = countsubqbds.multiply(prceQbcd).setScale(3, BigDecimal.ROUND_HALF_DOWN);
                                        money = money.add(cmcd);
                                        if (sfyc) {
                                            totalConsultMoney = BigDecimal.ZERO;
                                        } else {
                                            totalConsultMoney = totalConsultMoney.add(cmcd);
                                        }
                                    }
                                }
                            }
                            addCost.setMoney(money + "");
                        }
                    }
                    if (ToolUtil.isNotEmpty(r2.getPriceType()) && r2.getPriceType().equals("Range")) {
                        //参数范围
                        if (r2.getPriceCsbz().equals("By Quantity")) {
                            BigDecimal fwajs = BigDecimal.ZERO;
                            if (eachOrderCost) {
                                for (TransportDispatchResult llr : llist) {
                                    if (llr.getLineId().equals(r.getLineId())) {
                                        fwajs = new BigDecimal(llr.getTooDeployNum());
                                        break;
                                    }
                                }
                            } else {
                                fwajs = new BigDecimal(r.getTooDeployNum());
                            }
                            if (fwajs.compareTo(as) == 1) {
                                if ((fwajs.compareTo(csxx) != -1) && (fwajs.compareTo(cssx) != 1)) { //大于等于参数下限 效应等于参数上限
                                    if (r2.getPriceMode().equals("CNY/m³")) {
                                        BigDecimal b2mulvolume = volume.multiply(b2).setScale(3, BigDecimal.ROUND_HALF_DOWN);
                                        if (sfyc) {
                                            totalConsultMoney = BigDecimal.ZERO;
                                        } else {
                                            totalConsultMoney = totalConsultMoney.add(b2mulvolume);
                                        }

                                        addCost.setPriceMode(r2.getPriceMode());
                                        addCost.setPrice(b2 + "");
                                        addCost.setNums(volume + "");
                                        addCost.setMoney(b2mulvolume + "");
                                    }
                                    if (r2.getPriceMode().equals("CNY/Unit")) {
                                        BigDecimal b2num = num.multiply(b2).setScale(3, BigDecimal.ROUND_HALF_DOWN);
                                        if (sfyc) {
                                            totalConsultMoney = BigDecimal.ZERO;
                                        } else {
                                            totalConsultMoney = totalConsultMoney.add(b2num);
                                        }
                                        addCost.setPriceMode(r2.getPriceMode());
                                        addCost.setPrice(b2 + "");
                                        addCost.setNums(num + "");
                                        addCost.setMoney(b2num + "");
                                    }
                                    if (r2.getPriceMode().equals("CNY/Vehicle")) {
                                        if (sfyc) {
                                            totalConsultMoney = BigDecimal.ZERO;
                                        } else {
                                            totalConsultMoney = totalConsultMoney.add(b2);
                                        }

                                        addCost.setPriceMode(r2.getPriceMode());
                                        addCost.setPrice(b2 + "");
                                        addCost.setNums("1");
                                        addCost.setMoney(b2 + "");
                                    }
                                    if (r2.getPriceMode().equals("CNY/Km")) {
                                        if (licheng.compareTo(as) == 1) {
                                            BigDecimal b2licheng = licheng.multiply(b2).setScale(3, BigDecimal.ROUND_HALF_DOWN);
                                            if (sfyc) {
                                                totalConsultMoney = BigDecimal.ZERO;
                                            } else {
                                                totalConsultMoney = totalConsultMoney.add(b2licheng);
                                            }

                                            addCost.setPriceMode(r2.getPriceMode());
                                            addCost.setPrice(b2 + "");
                                            addCost.setNums(licheng + "");
                                            addCost.setMoney(b2licheng + "");
                                        }
                                    }
                                    if (r2.getPriceMode().equals("CNY/Point")) {
                                        addCost.setPriceMode(r2.getPriceMode());
                                        addCost.setPrice(priceQb + "");
                                        addCost.setV3(priceQbds + "");
                                        addCost.setV4(prceQbcd + "");
                                        BigDecimal money = priceQb;
                                        if (sfyc) {
                                            totalConsultMoney = BigDecimal.ZERO;
                                        } else {
                                            totalConsultMoney = totalConsultMoney.add(priceQb);
                                        }

                                        // 计算是否超点
                                        if (priceQbds.compareTo(as) == 1 && prceQbcd.compareTo(as) == 1) {
                                            TransportDispatchParam countppp = new TransportDispatchParam();
                                            countppp.setDispatchNumber(detail.getDispatchNumber());
                                            countppp.setLineId(r.getLineId());
                                            Integer countgg = transportDispatchService.countGetUnit(countppp);//合计该线路下  门店数
                                            if (countgg != null && countgg > 0) {
                                                addCost.setNums(countgg + "");
                                                BigDecimal bigcountgg = new BigDecimal(countgg);
                                                if (bigcountgg.compareTo(priceQbds) == 1) {//如果门店数 大于 起步点数
                                                    BigDecimal countsubqbds = bigcountgg.subtract(priceQbds);
                                                    BigDecimal cmcd = countsubqbds.multiply(prceQbcd).setScale(3, BigDecimal.ROUND_HALF_DOWN);
                                                    money = money.add(cmcd);
                                                    if (sfyc) {
                                                        totalConsultMoney = BigDecimal.ZERO;
                                                    } else {
                                                        totalConsultMoney = totalConsultMoney.add(cmcd);
                                                    }
                                                }
                                            }
                                        }
                                        addCost.setMoney(money + "");
                                    }
                                }

                            }
                        }
                        if (r2.getPriceCsbz().equals("By Volume m³")) {
                            BigDecimal fwatj = BigDecimal.ZERO;
                            if (eachOrderCost) {
                                for (TransportDispatchResult llr : llist) {
                                    if (llr.getLineId().equals(r.getLineId())) {
                                        fwatj = new BigDecimal(llr.getTooDeployVolume());
                                        break;
                                    }
                                }
                            } else {
                                fwatj = new BigDecimal(r.getTooDeployVolume());
                            }

                            if ((fwatj.compareTo(csxx) != -1) && (fwatj.compareTo(cssx) != 1)) { //大于等于参数下限 小于等于参数上限
                                if (r2.getPriceMode().equals("CNY/m³")) {
                                    BigDecimal b2mulvolume = volume.multiply(b2).setScale(3, BigDecimal.ROUND_HALF_DOWN);
                                    if (sfyc) {
                                        totalConsultMoney = BigDecimal.ZERO;
                                    } else {
                                        totalConsultMoney = totalConsultMoney.add(b2mulvolume);
                                    }

                                    addCost.setPriceMode(r2.getPriceMode());
                                    addCost.setPrice(b2 + "");
                                    addCost.setNums(volume + "");
                                    addCost.setMoney(b2mulvolume + "");
                                }
                                if (r2.getPriceMode().equals("CNY/Unit")) {
                                    BigDecimal b2num = num.multiply(b2).setScale(3, BigDecimal.ROUND_HALF_DOWN);
                                    if (sfyc) {
                                        totalConsultMoney = BigDecimal.ZERO;
                                    } else {
                                        totalConsultMoney = totalConsultMoney.add(b2num);
                                    }

                                    addCost.setPriceMode(r2.getPriceMode());
                                    addCost.setPrice(b2 + "");
                                    addCost.setNums(num + "");
                                    addCost.setMoney(b2num + "");
                                }
                                if (r2.getPriceMode().equals("CNY/Vehicle")) {
                                    if (sfyc) {
                                        totalConsultMoney = BigDecimal.ZERO;
                                    } else {
                                        totalConsultMoney = totalConsultMoney.add(b2);
                                    }

                                    addCost.setPriceMode(r2.getPriceMode());
                                    addCost.setPrice(b2 + "");
                                    addCost.setNums("1");
                                    addCost.setMoney(b2 + "");
                                }
                                if (r2.getPriceMode().equals("CNY/Km")) {
                                    if (licheng.compareTo(as) == 1) {
                                        BigDecimal b2licheng = licheng.multiply(b2).setScale(3, BigDecimal.ROUND_HALF_DOWN);
                                        if (sfyc) {
                                            totalConsultMoney = BigDecimal.ZERO;
                                        } else {
                                            totalConsultMoney = totalConsultMoney.add(b2licheng);
                                        }

                                        addCost.setPriceMode(r2.getPriceMode());
                                        addCost.setPrice(b2 + "");
                                        addCost.setNums(licheng + "");
                                        addCost.setMoney(b2licheng + "");
                                    }
                                }
                                if (r2.getPriceMode().equals("CNY/Point")) {
                                    addCost.setPriceMode(r2.getPriceMode());
                                    addCost.setPrice(priceQb + "");
                                    addCost.setV3(priceQbds + "");
                                    addCost.setV4(prceQbcd + "");
                                    BigDecimal money = priceQb;

                                    if (sfyc) {
                                        totalConsultMoney = BigDecimal.ZERO;
                                    } else {
                                        totalConsultMoney = totalConsultMoney.add(priceQb);
                                    }
                                    // 计算是否超点
                                    if (priceQbds.compareTo(as) == 1 && prceQbcd.compareTo(as) == 1) {
                                        TransportDispatchParam countppp = new TransportDispatchParam();
                                        countppp.setDispatchNumber(detail.getDispatchNumber());
                                        countppp.setLineId(r.getLineId());
                                        Integer countgg = transportDispatchService.countGetUnit(countppp);//合计该线路下  门店数
                                        if (countgg != null && countgg > 0) {
                                            addCost.setNums(countgg + "");
                                            BigDecimal bigcountgg = new BigDecimal(countgg);
                                            if (bigcountgg.compareTo(priceQbds) == 1) {//如果门店数 大于 起步点数
                                                BigDecimal countsubqbds = bigcountgg.subtract(priceQbds);
                                                BigDecimal cmcd = countsubqbds.multiply(prceQbcd).setScale(3, BigDecimal.ROUND_HALF_DOWN);
                                                money = money.add(cmcd);
                                                if (sfyc) {
                                                    totalConsultMoney = BigDecimal.ZERO;
                                                } else {
                                                    totalConsultMoney = totalConsultMoney.add(cmcd);
                                                }
                                            }
                                        }
                                    }
                                    addCost.setMoney(money + "");
                                }
                            }
                        }
                        if (r2.getPriceCsbz().equals("按公里")) {
                            if (ToolUtil.isNotEmpty(licheng)) {
                                if ((licheng.compareTo(csxx) != -1) && (licheng.compareTo(cssx) != 1)) { //大于等于参数下限 小于等于参数上限
                                    if (r2.getPriceMode().equals("CNY/m³")) {
                                        BigDecimal b2mulvolume = volume.multiply(b2).setScale(3, BigDecimal.ROUND_HALF_DOWN);
                                        if (sfyc) {
                                            totalConsultMoney = BigDecimal.ZERO;
                                        } else {
                                            totalConsultMoney = totalConsultMoney.add(b2mulvolume);
                                        }

                                        addCost.setPriceMode(r2.getPriceMode());
                                        addCost.setPrice(b2 + "");
                                        addCost.setNums(volume + "");
                                        addCost.setMoney(b2mulvolume + "");
                                    }
                                    if (r2.getPriceMode().equals("CNY/Unit")) {
                                        BigDecimal b2num = num.multiply(b2).setScale(3, BigDecimal.ROUND_HALF_DOWN);
                                        if (sfyc) {
                                            totalConsultMoney = BigDecimal.ZERO;
                                        } else {
                                            totalConsultMoney = totalConsultMoney.add(b2num);
                                        }

                                        addCost.setPriceMode(r2.getPriceMode());
                                        addCost.setPrice(b2 + "");
                                        addCost.setNums(num + "");
                                        addCost.setMoney(b2num + "");
                                    }
                                    if (r2.getPriceMode().equals("CNY/Vehicle")) {
                                        if (sfyc) {
                                            totalConsultMoney = BigDecimal.ZERO;
                                        } else {
                                            totalConsultMoney = totalConsultMoney.add(b2);
                                        }

                                        addCost.setPriceMode(r2.getPriceMode());
                                        addCost.setPrice(b2 + "");
                                        addCost.setNums("1");
                                        addCost.setMoney(b2 + "");
                                    }
                                    if (r2.getPriceMode().equals("CNY/Km")) {
                                        if (licheng.compareTo(as) == 1) {
                                            BigDecimal b2licheng = licheng.multiply(b2).setScale(3, BigDecimal.ROUND_HALF_DOWN);
                                            if (sfyc) {
                                                totalConsultMoney = BigDecimal.ZERO;
                                            } else {
                                                totalConsultMoney = totalConsultMoney.add(b2licheng);
                                            }

                                            addCost.setPriceMode(r2.getPriceMode());
                                            addCost.setPrice(b2 + "");
                                            addCost.setNums(licheng + "");
                                            addCost.setMoney(b2licheng + "");
                                        }
                                    }
                                    if (r2.getPriceMode().equals("CNY/Point")) {
                                        addCost.setPriceMode(r2.getPriceMode());
                                        addCost.setPrice(priceQb + "");
                                        addCost.setV3(priceQbds + "");
                                        addCost.setV4(prceQbcd + "");
                                        BigDecimal money = priceQb;
                                        if (sfyc) {
                                            totalConsultMoney = BigDecimal.ZERO;
                                        } else {
                                            totalConsultMoney = totalConsultMoney.add(priceQb);
                                        }
                                        // 计算是否超点
                                        if (priceQbds.compareTo(as) == 1 && prceQbcd.compareTo(as) == 1) {
                                            TransportDispatchParam countppp = new TransportDispatchParam();
                                            countppp.setDispatchNumber(detail.getDispatchNumber());
                                            countppp.setLineId(r.getLineId());
                                            Integer countgg = transportDispatchService.countGetUnit(countppp);//合计该线路下  门店数
                                            if (countgg != null && countgg > 0) {
                                                addCost.setNums(countgg + "");
                                                BigDecimal bigcountgg = new BigDecimal(countgg);
                                                if (bigcountgg.compareTo(priceQbds) == 1) {//如果门店数 大于 起步点数
                                                    BigDecimal countsubqbds = bigcountgg.subtract(priceQbds);
                                                    BigDecimal cmcd = countsubqbds.multiply(prceQbcd).setScale(3, BigDecimal.ROUND_HALF_DOWN);
                                                    money = money.add(cmcd);
                                                    if (sfyc) {
                                                        totalConsultMoney = BigDecimal.ZERO;
                                                    } else {
                                                        totalConsultMoney = totalConsultMoney.add(cmcd);
                                                    }
                                                }
                                            }
                                        }
                                        addCost.setMoney(money + "");
                                    }
                                }
                            }
                        }
                    }
                }
                costlist.add(addCost);
            }
            //装车费
            BigDecimal num = BigDecimal.ZERO;
            if (ToolUtil.isNotEmpty(r.getTooDeployNum())) {
                num = new BigDecimal(r.getTooDeployNum()); //获取数量
            }
            BigDecimal volume = BigDecimal.ZERO;
            if (ToolUtil.isNotEmpty(r.getTooDeployVolume())) {
                volume = new BigDecimal(r.getTooDeployVolume());  //获取体积
            }
            BasicLoadingQuotationParam loadingQuotationParam = new BasicLoadingQuotationParam();  //创建装车表对象
            loadingQuotationParam.setOperateId(detail.getOperateId()); //填入传入调度单号项目id
            loadingQuotationParam.setCarrierId(detail.getCarrierId()); //承运商
//				loadingQuotationParam.setLineId(r.getLineId());//线路
            loadingQuotationParam.setLoadingType(loadingType); //装运方
            BasicLoadingQuotationResult basicLoadingQuotationResult = basicLoadingQuotationService.findBySpec(loadingQuotationParam);
            if (basicLoadingQuotationResult != null && ToolUtil.isNotEmpty(basicLoadingQuotationResult.getPrice())) {
                if ("CNY/Vehicle".equals(basicLoadingQuotationResult.getPriceMode())) {
                    BigDecimal price = new BigDecimal(basicLoadingQuotationResult.getPrice());
                    loadingMoney = loadingMoney.add(price.setScale(3, BigDecimal.ROUND_HALF_DOWN));
                } else if ("CNY/Unit".equals(basicLoadingQuotationResult.getPriceMode())) {
                    BigDecimal price = new BigDecimal(basicLoadingQuotationResult.getPrice());
                    loadingMoney = loadingMoney.add(price.multiply(num).setScale(3, BigDecimal.ROUND_HALF_DOWN));
                } else if ("CNY/m³".equals(basicLoadingQuotationResult.getPriceMode())) {
                    BigDecimal price = new BigDecimal(basicLoadingQuotationResult.getPrice());
                    loadingMoney = loadingMoney.add(price.multiply(volume).setScale(3, BigDecimal.ROUND_HALF_DOWN));
                }
            }
        }
        //临时车不计算运费
//		if(detail.getCarrierName() != null && detail.getCarrierName().contains("临时车")){
//			totalConsultMoney = as;
//		}
        tDispatchService.lambdaUpdate()
                .eq(TDispatch::getDispatchNumber, dispatchNumber)
                .set(TDispatch::getMileageTraveled, mileageTraveled)
                .set(TDispatch::getConsultMoney, totalConsultMoney)
                .set(TDispatch::getFreightMoney, totalConsultMoney)
                .set(TDispatch::getLoadingType, loadingType)
                .set(TDispatch::getLoadingMoney, loadingMoney)
                .set(TDispatch::getCalculateShippingCost, "Yes")
                .update();
        if (costlist.size() > 0) {
            // 移除null值
//			costlist.removeIf(item -> item.getPriceMode() == null);
            TransportCostParam delete = new TransportCostParam();
            delete.setDispatchNumber(dispatchNumber);
            transportCostService.deleteBySpec(delete);
            transportCostService.saveBatch(costlist);
        }
        tDispatchParam.setConsultMoney(totalConsultMoney + "");
        if (detail.getCarrierName() != null && detail.getCarrierName().contains("Temporary Vehicle")) {
            tDispatchParam.setFreightMoney("");
        } else {
            tDispatchParam.setFreightMoney(totalConsultMoney + "");
        }
        tDispatchParam.setLoadingMoney(loadingMoney + "");
        return ResponseData.success(tDispatchParam);
    }

    @Autowired
    private BasicLineService basicLineService;

    @Autowired
    private TransportStevedoreSigninService transportStevedoreSigninService;

    /**
     * 调整费用
     */
    @RequestMapping("/editItem2")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public ResponseData editItem2(TDispatchParam tDispatchParam, String[] loadingNumbers) {
        User user = userService.getcurrentUser();
        BigDecimal as = new BigDecimal("0");
        if (ToolUtil.isNotEmpty(tDispatchParam.getMileageTraveled())) {
            BigDecimal mileageTraveledbig = new BigDecimal(tDispatchParam.getMileageTraveled());
            if (mileageTraveledbig.compareTo(as) != 1) {
                return ResponseData.error("Mileage must be greater than 0");
            }
        } else {
            if (!tDispatchParam.getChengyunfangshi().equals("Express") && !tDispatchParam.getChengyunfangshi().equals("Logistics")) {
                return ResponseData.error("Mileage must be greater than 0");
            }
        }
        String message = "";
        tDispatchParam.setDeptId(user.getDeptId());
        TDispatchResult dispatchResult = tDispatchService.findBySpec(tDispatchParam, user.getOperateId());
        if ("PENDING_REPORT".equals(dispatchResult.getStateTb())) {
            return ResponseData.error("[PENDING_REPORT]cannot be operated！");
        }
        if (tDispatchParam.getCarrierId() != null && dispatchResult.getCarrierId() != null) {
            if (!tDispatchParam.getCarrierId().equals(dispatchResult.getCarrierId())) {
                BasicPrivatecar car = basicPrivatecarService.getById(dispatchResult.getCarId());
                if (car != null) {
                    BasicDriver driver = basicDriverService.getById(car.getDriverId1());
                    if (driver != null) {
                        BasicCarrier ybasicCarrier = basicCarrierService.getById(dispatchResult.getCarrierId());
                        BasicCarrier basicCarrier = basicCarrierService.getById(tDispatchParam.getCarrierId());
                        if (ybasicCarrier != null && basicCarrier != null && !ybasicCarrier.getOperateId().equals(basicCarrier.getOperateId())) {
                            if (driver.getUserId() != null) {
                                userService.lambdaUpdate()
                                        .eq(User::getUserId, driver.getUserId())
                                        .set(User::getOperateId, basicCarrier.getOperateId())
                                        .set(User::getDeptId, basicCarrier.getDeptId())
                                        .update();
                            }

                            BasicDriverParam BasicDriverParamupdate = new BasicDriverParam();
                            BasicDriverParamupdate.setId(driver.getId());
                            BasicDriverParamupdate.setDeptId(basicCarrier.getDeptId());
                            BasicDriverParamupdate.setDriverOperateId(Integer.parseInt(basicCarrier.getOperateId().toString()));
                            BasicDriverParamupdate.setDriverOperateName(basicCarrier.getOperateName());
                            basicDriverService.update(BasicDriverParamupdate);

                            BasicPrivatecarParam BasicPrivatecarParamupdate = new BasicPrivatecarParam();
                            BasicPrivatecarParamupdate.setId(car.getId());
                            BasicPrivatecarParamupdate.setDeptId(basicCarrier.getDeptId());
                            BasicPrivatecarParamupdate.setOperateId(basicCarrier.getOperateId());
                            BasicPrivatecarParamupdate.setOperateName(basicCarrier.getOperateName());
                            basicPrivatecarService.update(BasicPrivatecarParamupdate);
                        }
                    }
                    BasicPrivatecarParam updatecar = new BasicPrivatecarParam();
                    updatecar.setId(car.getId());
                    updatecar.setPrivatecarFleetId(Integer.parseInt(tDispatchParam.getCarrierId().toString()));
                    updatecar.setPrivatecarFleetName(tDispatchParam.getCarrierName());
                    basicPrivatecarService.update(updatecar);
                }
            }
        }
        BasicOperate basicOperate = basicOperateService.getById(dispatchResult.getOperateId());
        if (dispatchResult != null) {
            if (ToolUtil.isNotEmpty(dispatchResult.getCalculateShippingCost()) && !dispatchResult.getCalculateShippingCost().equals("Yes")) {
                return ResponseData.error("Please Generate Freight");
            }
            if (!dispatchResult.getTstate().equals("PENDING_PRICING") || !dispatchResult.getTstate().equals("REJECTED")) {
                if (tDispatchParam.getLoadingType().equals("Self-loading")) {
                    tDispatchParam.setLoadingPersonnel("Self-loading");
                } else if (tDispatchParam.getLoadingType().equals("Warehouse")) {
                    if (loadingNumbers != null) {
                        String sloadingPersonnel = "";
                        String loadingNumbersp = "";
                        for (int i = 0; i < loadingNumbers.length; i++) {
                            String loadingNumber = loadingNumbers[i];
                            if (ToolUtil.isNotEmpty(loadingNumber)) {
                                TransportStevedoreSigninParam stevedoreSigninParam = new TransportStevedoreSigninParam();
                                stevedoreSigninParam.setAuditBy(loadingNumber);
                                stevedoreSigninParam.setDeptId(user.getDeptId());
                                TransportStevedoreSigninResult signres = transportStevedoreSigninService.findBySpec(stevedoreSigninParam, user.getOperateId());
                                if (signres != null) {
                                    sloadingPersonnel += signres.getAuditTime();
                                    loadingNumbersp += loadingNumber;
                                    if (loadingNumbers.length != i + 1) {
                                        sloadingPersonnel += "+";
                                        loadingNumbersp += ",";
                                    }
                                }
                            }
                        }
                        tDispatchParam.setLoadingNumber(loadingNumbersp);
                        tDispatchParam.setLoadingPersonnel(sloadingPersonnel);
                    }
                }

                //计算每单实际金额
                BigDecimal freightMoney = new BigDecimal(tDispatchParam.getFreightMoney());
                BigDecimal money = new BigDecimal(tDispatchParam.getFreightMoney());
                BigDecimal loadingMoney = new BigDecimal("0");
                if (ToolUtil.isNotEmpty(tDispatchParam.getLoadingMoney())) {//装车费
                    loadingMoney = new BigDecimal(tDispatchParam.getLoadingMoney());
                    if (loadingMoney.compareTo(as) == 1) {
                        money = money.add(loadingMoney).setScale(3, BigDecimal.ROUND_HALF_DOWN);
                    }
                }
                tDispatchParam.setMoney(money + "");
                if (ToolUtil.isNotEmpty(basicOperate.getEachOrderCost()) && basicOperate.getEachOrderCost().equals("Yes")) {
                    if (freightMoney.compareTo(as) == 0) {
                        TransportCostParam costParam = new TransportCostParam();
                        costParam.setDispatchNumber(dispatchResult.getDispatchNumber());
                        List<TransportCostResult> list = transportCostService.findListBySpecS(costParam);
                        for (TransportCostResult cr : list) {
                            costParam.setV2("0");
                            costParam.setId(cr.getId());
                            transportCostService.update(costParam);
                        }
                    } else {
                        BigDecimal consultMoney = new BigDecimal("0");
                        if (ToolUtil.isNotEmpty(dispatchResult.getConsultMoney())) {
                            consultMoney = new BigDecimal(dispatchResult.getConsultMoney());
                        }
                        if (freightMoney.compareTo(consultMoney) != 0) {
                            BigDecimal toovolume = new BigDecimal(dispatchResult.getToovolume());//总体积
                            BigDecimal consultPrice = freightMoney.divide(toovolume, 8, BigDecimal.ROUND_HALF_DOWN);//金额 / 总体积 =  实际单方价格
                            TransportCostParam costParam = new TransportCostParam();
                            costParam.setDispatchNumber(dispatchResult.getDispatchNumber());
                            List<TransportCostResult> list = transportCostService.findListBySpecS(costParam);
                            for (TransportCostResult cr : list) {
                                BigDecimal nums = new BigDecimal(cr.getNums());//体积
                                BigDecimal dmoney = nums.multiply(consultPrice).setScale(3, BigDecimal.ROUND_HALF_DOWN);//订单体积 * 实际单方价格 = 订单实际价格
                                costParam.setV2(dmoney.toString());
                                costParam.setId(cr.getId());
                                transportCostService.update(costParam);
                            }
                        }
                    }
                } else {
                    TransportCostParam costParam = new TransportCostParam();
                    costParam.setDispatchNumber(dispatchResult.getDispatchNumber());
                    List<TransportCostResult> list = transportCostService.findListBySpecS(costParam);
                    for (TransportCostResult cr : list) {
                        costParam.setV2("0");
                        costParam.setId(cr.getId());
                        transportCostService.update(costParam);
                    }
                }
                tDispatchParam.setId(dispatchResult.getId());
                this.tDispatchService.update(tDispatchParam);
            }
        }
        ResponseData data = new ResponseData();
        data.setSuccess(true);
        data.setMessage(message);
        return data;
    }

    /**
     * @param tDispatchParam
     * @return
     */
    @RequestMapping("/getTs")
    @ResponseBody
    public ResponseData getTs(TDispatchParam tDispatchParam) {
        SimpleDateFormat sdf10 = new SimpleDateFormat("yyyy-MM-dd");
        TDispatch tDispatch = tDispatchService.lambdaQuery()
                .eq(TDispatch::getDispatchNumber, tDispatchParam.getDispatchNumber())
                .one();
        if (tDispatch == null) {
            return ResponseData.success();
        }

        BasicOperate one = basicOperateService.lambdaQuery().eq(BasicOperate::getId, tDispatch.getOperateId()).one();
        if (one != null && "Yes".equals(one.getCalculateShippingCost())) {

            // 查找地址中是否配置了线路，若未配置则提示
            List<TransportDispatch> transportDispatchList = transportDispatchService.lambdaQuery()
                    .eq(TransportDispatch::getDispatchNumber, tDispatchParam.getDispatchNumber())
                    .list();
            List<String> transportNumberList = new ArrayList<>();
            for (TransportDispatch obj : transportDispatchList) {
                if (ToolUtil.isNotEmpty(obj.getTransportNumber())) {
                    transportNumberList.add(obj.getTransportNumber());
                }
            }
            if (ToolUtil.isNotEmpty(transportNumberList)) {
                List<OrderTransport> orderTransportList = this.orderTransportService.lambdaQuery()
                        .in(OrderTransport::getTransportNumber, transportNumberList)
                        .list();
                Set<Integer> addrIdList = new HashSet<>();
                Map<String, List<Integer>> linesMap = new HashMap<>();
                StringBuffer errStr = new StringBuffer();
                for (OrderTransport obj : orderTransportList) {
                    if (ToolUtil.isEmpty(obj.getLineId())) {
                        if (ToolUtil.isNotEmpty(obj.getGetLocationId())) {
                            addrIdList.add(obj.getGetLocationId().intValue());
                            if (linesMap.get(obj.getGetLocationId().toString()) == null) {
                                List<Integer> orderTransportIdList = new ArrayList<>();
                                orderTransportIdList.add(obj.getId());
                                linesMap.put(obj.getGetLocationId().toString(), orderTransportIdList);
                            } else {
                                List<Integer> orderTransportIdList = linesMap.get(obj.getGetLocationId().toString());
                                orderTransportIdList.add(obj.getId());
                                linesMap.put(obj.getGetLocationId().toString(), orderTransportIdList);
                            }
                        } else {
                            if (errStr.length() > 0) {
                                errStr.append("<br>");
                            }
                            errStr.append("Store[").append(obj.getGetUnit())
                                    .append("]Route not set！");
                        }
                    }
                }
                if (ToolUtil.isNotEmpty(addrIdList)) {
                    List<BasicAddress> addrList = basicAddressService.lambdaQuery()
                            .in(BasicAddress::getId, addrIdList)
                            .list();
                    for (BasicAddress obj : addrList) {
                        if (ToolUtil.isNotEmpty(obj.getLineId())) {
                            if (linesMap.get(obj.getId().toString()) != null) {
                                this.orderTransportService.lambdaUpdate()
                                        .in(OrderTransport::getId, linesMap.get(obj.getId().toString()))
                                        .set(OrderTransport::getLineId, obj.getLineId())
                                        .set(OrderTransport::getLineName, obj.getLineName())
                                        .update();
                            }
                        } else {
                            if (errStr.length() > 0) {
                                errStr.append("<br>");
                            }
                            errStr.append("Store[").append(obj.getPutgoodsName())
                                    .append("]Route not set！");
                        }
                    }
                }
                if (errStr.length() > 0) {
                    errStr.append("<br>");
                    errStr.append("Operation not allowed! Please set the route first.");
                    return ResponseData.error(400, errStr.toString());
                }
            }

            if (ToolUtil.isNotEmpty(tDispatch.getCarId())) {
                List<OrderOutpreparePlatooncar> orderOutpreparePlatooncarList = this.orderOutpreparePlatooncarService.lambdaQuery()
                        .eq(OrderOutpreparePlatooncar::getCarId, tDispatch.getCarId())
                        .eq(OrderOutpreparePlatooncar::getEstDeliveryDate, sdf10.format(new Date()))
                        .list();
                if (orderOutpreparePlatooncarList == null || orderOutpreparePlatooncarList.size() < 1) {
                    return ResponseData.success();
                }
                List<String> xlbClientIdList = new ArrayList<>();
                for (OrderOutpreparePlatooncar obj : orderOutpreparePlatooncarList) {
                    xlbClientIdList.add(obj.getClientId());
                }
                List<OrderTransportResult> orderTransportList = this.orderTransportService.findGetUnitVol(tDispatch.getOperateId(), xlbClientIdList);

                StringBuffer errStr = new StringBuffer();
                for (OrderTransportResult obj : orderTransportList) {
                    if (errStr.length() > 0) {
                        errStr.append("<br>");
                    }
                    errStr.append("Store[").append(obj.getGetUnit())
                            .append("]Should be loaded").append(obj.getTotalVolume())
                            .append("Loaded").append(obj.getTooVolume());
                }
                if (errStr.length() > 0) {
                    errStr.append("<br>");
                    errStr.append("Operation not allowed! Please set the route first.");
                    return ResponseData.error(400, errStr.toString());
                }
            }

        }
        if (one != null && (ToolUtil.isEmpty(one.getCalculateShippingCost()) || "No".equals(one.getCalculateShippingCost()))) {

            // 原有逻辑
            List<TransportDispatch> transportDispatchList = transportDispatchService.lambdaQuery()
                    .eq(TransportDispatch::getDispatchNumber, tDispatchParam.getDispatchNumber())
                    .list();
            List<String> transportNumberList = new ArrayList<>();
            for (TransportDispatch obj : transportDispatchList) {
                if (ToolUtil.isNotEmpty(obj.getTransportNumber())) {
                    transportNumberList.add(obj.getTransportNumber());
                }
            }
            if (ToolUtil.isNotEmpty(transportNumberList)) {
                List<OrderTransport> orderTransportList = this.orderTransportService.lambdaQuery()
                        .in(OrderTransport::getTransportNumber, transportNumberList)
                        .list();
                Set<Integer> addrIdList = new HashSet<>();
                Map<String, List<Integer>> linesMap = new HashMap<>();
                StringBuffer errStr = new StringBuffer();
                for (OrderTransport obj : orderTransportList) {
                    if (ToolUtil.isEmpty(obj.getLineId())) {
                        if (ToolUtil.isNotEmpty(obj.getGetLocationId())) {
                            addrIdList.add(obj.getGetLocationId().intValue());
                            if (linesMap.get(obj.getGetLocationId().toString()) == null) {
                                List<Integer> orderTransportIdList = new ArrayList<>();
                                orderTransportIdList.add(obj.getId());
                                linesMap.put(obj.getGetLocationId().toString(), orderTransportIdList);
                            } else {
                                List<Integer> orderTransportIdList = linesMap.get(obj.getGetLocationId().toString());
                                orderTransportIdList.add(obj.getId());
                                linesMap.put(obj.getGetLocationId().toString(), orderTransportIdList);
                            }
                        } else {
                            if (errStr.length() > 0) {
                                errStr.append("<br>");
                            }
                            errStr.append("Store[").append(obj.getGetUnit())
                                    .append("]Route not set！");
                        }
                    }
                }
                if (ToolUtil.isNotEmpty(addrIdList)) {
                    List<BasicAddress> addrList = basicAddressService.lambdaQuery()
                            .in(BasicAddress::getId, addrIdList)
                            .list();
                    for (BasicAddress obj : addrList) {
                        if (ToolUtil.isNotEmpty(obj.getLineId())) {
                            if (linesMap.get(obj.getId().toString()) != null) {
                                this.orderTransportService.lambdaUpdate()
                                        .in(OrderTransport::getId, linesMap.get(obj.getId().toString()))
                                        .set(OrderTransport::getLineId, obj.getLineId())
                                        .set(OrderTransport::getLineName, obj.getLineName())
                                        .update();
                            }
                        } else {
                            if (errStr.length() > 0) {
                                errStr.append("<br>");
                            }
                            errStr.append("Store[").append(obj.getPutgoodsName())
                                    .append("]Route not set！");
                        }
                    }
                }
                if (errStr.length() > 0) {
                    errStr.append("<br>");
                    errStr.append("Are you sure you want to perform this operation？");
                    return ResponseData.error(errStr.toString());
                }
            }

            if (ToolUtil.isNotEmpty(tDispatch.getCarId())) {
                List<OrderOutpreparePlatooncar> orderOutpreparePlatooncarList = this.orderOutpreparePlatooncarService.lambdaQuery()
                        .eq(OrderOutpreparePlatooncar::getCarId, tDispatch.getCarId())
                        .eq(OrderOutpreparePlatooncar::getEstDeliveryDate, sdf10.format(new Date()))
                        .list();
                if (orderOutpreparePlatooncarList == null || orderOutpreparePlatooncarList.size() < 1) {
                    return ResponseData.success();
                }
                List<String> xlbClientIdList = new ArrayList<>();
                for (OrderOutpreparePlatooncar obj : orderOutpreparePlatooncarList) {
                    xlbClientIdList.add(obj.getClientId());
                }
                List<OrderTransportResult> orderTransportList = this.orderTransportService.findGetUnitVol(tDispatch.getOperateId(), xlbClientIdList);

                StringBuffer errStr = new StringBuffer();
                for (OrderTransportResult obj : orderTransportList) {
                    if (errStr.length() > 0) {
                        errStr.append("<br>");
                    }
                    errStr.append("Store[").append(obj.getGetUnit())
                            .append("]Should be loaded").append(obj.getTotalVolume())
                            .append("Loaded").append(obj.getTooVolume());
                }
                if (errStr.length() > 0) {
                    errStr.append("<br>");
                    errStr.append("Are you sure you want to perform this operation？");
                    return ResponseData.error(errStr.toString());
                }
            }

        }


        return ResponseData.success();
    }

    /**
     * 确定费用
     */
    @RequestMapping("/editItem")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public ResponseData editItem(TDispatchParam tDispatchParam, String[] loadingNumbers) {
        User user = userService.getcurrentUser();
        BigDecimal as = new BigDecimal("0");
        if (ToolUtil.isNotEmpty(tDispatchParam.getMileageTraveled())) {
            BigDecimal mileageTraveledbig = new BigDecimal(tDispatchParam.getMileageTraveled());
            if (mileageTraveledbig.compareTo(as) != 1) {
                return ResponseData.error("Mileage must be greater than 0");
            }
        } else {
            if (!tDispatchParam.getChengyunfangshi().equals("Express") && !tDispatchParam.getChengyunfangshi().equals("Logistics")) {
                return ResponseData.error("Mileage must be greater than 0");
            }
        }
        String message = "";
        tDispatchParam.setDeptId(user.getDeptId());
        TDispatchResult dispatchResult = tDispatchService.findBySpec(tDispatchParam, user.getOperateId());
        if (tDispatchParam.getCarrierId() != null && dispatchResult.getCarrierId() != null) {
            if (!tDispatchParam.getCarrierId().equals(dispatchResult.getCarrierId())) {
                BasicPrivatecar car = basicPrivatecarService.getById(dispatchResult.getCarId());
                if (car != null) {
                    BasicDriver driver = basicDriverService.getById(car.getDriverId1());
                    if (driver != null) {
                        BasicCarrier ybasicCarrier = basicCarrierService.getById(dispatchResult.getCarrierId());
                        BasicCarrier basicCarrier = basicCarrierService.getById(tDispatchParam.getCarrierId());
                        if (ToolUtil.isEmpty(ybasicCarrier) || !ybasicCarrier.getOperateId().equals(basicCarrier.getOperateId())) {
                            if (driver.getUserId() != null) {
                                userService.lambdaUpdate()
                                        .eq(User::getUserId, driver.getUserId())
                                        .set(User::getOperateId, basicCarrier.getOperateId())
                                        .set(User::getDeptId, basicCarrier.getDeptId())
                                        .update();
                            }

                            BasicDriverParam BasicDriverParamupdate = new BasicDriverParam();
                            BasicDriverParamupdate.setId(driver.getId());
                            BasicDriverParamupdate.setDeptId(basicCarrier.getDeptId());
                            BasicDriverParamupdate.setDriverOperateId(Integer.parseInt(basicCarrier.getOperateId().toString()));
                            BasicDriverParamupdate.setDriverOperateName(basicCarrier.getOperateName());
                            basicDriverService.update(BasicDriverParamupdate);

                            BasicPrivatecarParam BasicPrivatecarParamupdate = new BasicPrivatecarParam();
                            BasicPrivatecarParamupdate.setId(car.getId());
                            BasicPrivatecarParamupdate.setDeptId(basicCarrier.getDeptId());
                            BasicPrivatecarParamupdate.setOperateId(basicCarrier.getOperateId());
                            BasicPrivatecarParamupdate.setOperateName(basicCarrier.getOperateName());
                            basicPrivatecarService.update(BasicPrivatecarParamupdate);
                        }
                    }
                    BasicPrivatecarParam updatecar = new BasicPrivatecarParam();
                    updatecar.setId(car.getId());
                    updatecar.setPrivatecarFleetId(Integer.parseInt(tDispatchParam.getCarrierId().toString()));
                    updatecar.setPrivatecarFleetName(tDispatchParam.getCarrierName());
                    basicPrivatecarService.update(updatecar);
                }
            }
        }
        BasicOperate basicOperate = basicOperateService.getById(dispatchResult.getOperateId());
        if (dispatchResult != null) {
//			if(ToolUtil.isNotEmpty(dispatchResult.getCalculateShippingCost())&&!dispatchResult.getCalculateShippingCost().equals("Yes")) {
//				return ResponseData.error("请生成运费");
//			}
            if (dispatchResult.getTstate().equals("PENDING_PRICING") || dispatchResult.getTstate().equals("REJECTED")) {
                if (tDispatchParam.getLoadingType().equals("Self-loading")) {
                    tDispatchParam.setLoadingPersonnel("Self-loading");
                } else if (tDispatchParam.getLoadingType().equals("Warehouse")) {
                    if (loadingNumbers != null) {
                        String sloadingPersonnel = "";
                        String loadingNumbersp = "";
                        for (int i = 0; i < loadingNumbers.length; i++) {
                            String loadingNumber = loadingNumbers[i];
                            if (ToolUtil.isNotEmpty(loadingNumber)) {
                                TransportStevedoreSigninParam stevedoreSigninParam = new TransportStevedoreSigninParam();
                                stevedoreSigninParam.setAuditBy(loadingNumber);
                                stevedoreSigninParam.setDeptId(user.getDeptId());
                                TransportStevedoreSigninResult signres = transportStevedoreSigninService.findBySpec(stevedoreSigninParam, user.getOperateId());
                                if (signres != null) {
                                    sloadingPersonnel += signres.getAuditTime();
                                    loadingNumbersp += loadingNumber;
                                    if (loadingNumbers.length != i + 1) {
                                        sloadingPersonnel += "+";
                                        loadingNumbersp += ",";
                                    }
                                }
                            }
                        }
                        tDispatchParam.setLoadingNumber(loadingNumbersp);
                        tDispatchParam.setLoadingPersonnel(sloadingPersonnel);
                    }
                }

                //计算每单实际金额
//    			BigDecimal freightMoney = new BigDecimal(tDispatchParam.getFreightMoney());
//    			BigDecimal money = new BigDecimal(tDispatchParam.getFreightMoney());
//        		BigDecimal loadingMoney = new BigDecimal("0");
//        		if(ToolUtil.isNotEmpty(tDispatchParam.getLoadingMoney())) {//装车费
//        			loadingMoney = new BigDecimal(tDispatchParam.getLoadingMoney());
//        			if(loadingMoney.compareTo(as) == 1) {
//        				money = money.add(loadingMoney).setScale(3, BigDecimal.ROUND_HALF_DOWN);
//        			}
//        		}
//    			if(ToolUtil.isNotEmpty(basicOperate.getEachOrderCost())&&basicOperate.getEachOrderCost().equals("Yes")) {
//        			if(freightMoney.compareTo(as) == 0) {
//            			TransportCostParam costParam = new TransportCostParam();
//            			costParam.setDispatchNumber(dispatchResult.getDispatchNumber());
//            			List<TransportCostResult> list = transportCostService.findListBySpecS(costParam);
//    	                for (TransportCostResult cr : list) {
//                			costParam.setV2("0");
//                			costParam.setId(cr.getId());
//                			transportCostService.update(costParam);
//    					}
//        			} else {
//            			BigDecimal consultMoney = new BigDecimal("0");
//        				if(ToolUtil.isNotEmpty(dispatchResult.getConsultMoney())) {
//                			consultMoney = new BigDecimal(dispatchResult.getConsultMoney());
//        				}
//        				if(freightMoney.compareTo(consultMoney) != 0) {
//                			BigDecimal toovolume = new BigDecimal(dispatchResult.getToovolume());//总体积
//                			BigDecimal consultPrice = freightMoney.divide(toovolume,8,BigDecimal.ROUND_HALF_DOWN);//金额 / 总体积 =  实际单方价格
//                			TransportCostParam costParam = new TransportCostParam();
//                			costParam.setDispatchNumber(dispatchResult.getDispatchNumber());
//                			List<TransportCostResult> list = transportCostService.findListBySpecS(costParam);
//        	                for (TransportCostResult cr : list) {
//                    			BigDecimal nums = new BigDecimal(cr.getNums());//体积
//                    			BigDecimal dmoney = nums.multiply(consultPrice).setScale(3, BigDecimal.ROUND_HALF_DOWN);//订单体积 * 实际单方价格 = 订单实际价格
//                    			costParam.setV2(dmoney.toString());
//                    			costParam.setId(cr.getId());
//                    			transportCostService.update(costParam);
//    						}
//        				}
//        			}
//    			} else {
//        			TransportCostParam costParam = new TransportCostParam();
//        			costParam.setDispatchNumber(dispatchResult.getDispatchNumber());
//        			List<TransportCostResult> list = transportCostService.findListBySpecS(costParam);
//	                for (TransportCostResult cr : list) {
//            			costParam.setV2("0");
//            			costParam.setId(cr.getId());
//            			transportCostService.update(costParam);
//					}
//    			}

                //根据封箱数量  更新派车明细换算数量
//    			if(ToolUtil.isNotEmpty(tDispatchParam.getSealingNumber())) {
//        			BigDecimal sealingNumber = new BigDecimal(tDispatchParam.getSealingNumber());
//        			TransportDispatchParam clParam = new TransportDispatchParam();
//        			clParam.setDispatchNumber(tDispatchParam.getDispatchNumber());
//        			List<TransportDispatchResult> cllist = transportDispatchService.findClListBySpec(clParam);//拆零派车明细
//        			if(cllist.size() > 0) {
//            			BigDecimal dispatchs = new BigDecimal(cllist.size());
//            			BigDecimal newmatrixingNumber = sealingNumber.divide(dispatchs,3,BigDecimal.ROUND_HALF_DOWN);
//						UpdateWrapper<TransportDispatch> updateWrapper = new UpdateWrapper<TransportDispatch>();
//						updateWrapper.set("matrixing_number", newmatrixingNumber);
//						updateWrapper.eq("dispatch_number", tDispatchParam.getDispatchNumber());
//						updateWrapper.eq("goods_number", "cl1");
//						transportDispatchService.update(updateWrapper);
//        			}
//    			}

//        		if(ToolUtil.isNotEmpty(dispatchResult.getConsultMoney())){
//        			BigDecimal consultMoney = new BigDecimal(dispatchResult.getConsultMoney());
//        			if(consultMoney.compareTo(as) == 1) {//参考价大于0
//        				if(freightMoney.compareTo(consultMoney) == 1) {//金额大于  参考价
//        	            	tDispatchParam.setId(dispatchResult.getId());
//        	            	tDispatchParam.setTstate("待审核");
//        	                this.tDispatchService.update(tDispatchParam);
//        	                ResponseData data = new ResponseData();
//        	                data.setSuccess(true);
//        	                data.setCode(403);
//                    		message += "请等待审核";
//        	                data.setMessage(message);
//        	                return data;
//        				}
//        			}
//        		} 

//        		if(ToolUtil.isNotEmpty(tDispatchParam.getXiechefei())) {
//        			BigDecimal xiechefei = new BigDecimal(tDispatchParam.getXiechefei());
//        			money = money.add(xiechefei).setScale(3, BigDecimal.ROUND_HALF_UP);
//        		}
                TDispatchParam param = new TDispatchParam();
                param.setDeptId(user.getDeptId());
                param.setDeliverId(user.getDeliverId());
                param.setFulllv(tDispatchParam.getStartDate());
                Integer trainNumber = tDispatchService.countCarnumber(param, user.getOperateId());//查询发运车次
//            	tDispatchParam.setMoney(money.toString());
                if (trainNumber == null) {
                    tDispatchParam.setTrainNumber("1");
                } else {
                    tDispatchParam.setTrainNumber((trainNumber + 1) + "");
                }
                tDispatchParam.setPaiType("web");

                TransportMsgParam dcqd = new TransportMsgParam();
                dcqd.setV3(dispatchResult.getCarId() + "");
                dcqd.setDeptId(user.getDeptId());
                dcqd.setStatus("Check-in at Warehouse");
                TransportMsgResult msgResult = transportMsgService.findDcqdBySpec(dcqd, user.getOperateId());
                if (msgResult != null) {
                    TransportMsgParam transportMsgParam = new TransportMsgParam();
                    transportMsgParam.setDispatchNumber(dispatchResult.getDispatchNumber());
                    transportMsgParam.setStatus("Warehouse Loading");
                    transportMsgParam.setMsgType("Driver");
                    transportMsgParam.setContent(dispatchResult.getCarnumber() + "Arrived at the warehouse and started loading。" + "Current Location：" + msgResult.getContent());
                    transportMsgParam.setTimes(msgResult.getTimes());
                    transportMsgParam.setCreateUsername(msgResult.getCreateUsername());
                    transportMsgParam.setDeliverId(user.getDeliverId());
                    transportMsgParam.setDeptId(user.getDeptId());
                    transportMsgParam.setSfyz("Yes");
                    transportMsgParam.setOpenId(msgResult.getOpenId());
                    transportMsgService.add(transportMsgParam);

                    tDispatchParam.setId(dispatchResult.getId());
                    tDispatchParam.setTstate("PENDING_DISPATCH");
                    this.tDispatchService.update(tDispatchParam);
                } else {
                    if (ToolUtil.isNotEmpty(basicOperate.getQdDriver()) && basicOperate.getQdDriver().equals("Yes")) {
                        message += "Check-in not detected! Please complete warehouse check-in first on your next arrival.";
                        TransportMsgParam transportMsgParam = new TransportMsgParam();
                        transportMsgParam.setStatus("Check-in at Warehouse");
                        transportMsgParam.setMsgType("System");
                        transportMsgParam.setTimes(tDispatchParam.getStartDate());
                        transportMsgParam.setV1(dispatchResult.getCarnumber());
                        transportMsgParam.setV2(dispatchResult.getSijidianhua());
                        transportMsgParam.setV3(dispatchResult.getCarId() + "");
                        transportMsgParam.setCreateUsername(dispatchResult.getSiji() + ",System Automatic Check-in");
                        transportMsgParam.setDeptId(user.getDeptId());
                        transportMsgParam.setDeliverId(user.getDeliverId());
                        transportMsgService.add(transportMsgParam);

                        TransportMsgParam transportMsgParam2 = new TransportMsgParam();
                        transportMsgParam2.setDispatchNumber(dispatchResult.getDispatchNumber());
                        transportMsgParam2.setStatus("Warehouse Loading");
                        transportMsgParam2.setMsgType("System");
                        transportMsgParam2.setContent(dispatchResult.getCarnumber() + "Arrived at the warehouse and started loading。");
                        transportMsgParam2.setTimes(tDispatchParam.getStartDate());
                        transportMsgParam2.setCreateUsername(user.getName());
                        transportMsgParam2.setDeliverId(user.getDeliverId());
                        transportMsgParam2.setDeptId(user.getDeptId());
                        transportMsgService.add(transportMsgParam2);

                        tDispatchParam.setId(dispatchResult.getId());
                        tDispatchParam.setTstate("PENDING_DISPATCH");
                        this.tDispatchService.update(tDispatchParam);
                    } else {
                        tDispatchParam.setId(dispatchResult.getId());
                        tDispatchParam.setTstate("PRICED");
                        this.tDispatchService.update(tDispatchParam);
                    }
                }
            }
        }
        ResponseData data = new ResponseData();
        data.setSuccess(true);
        data.setMessage(message);
        return data;
    }

    @Autowired
    private TransportMsgService transportMsgService;

    /**
     * to编辑运输单 明细
     */
    @RequestMapping("/tochecktooyedit")
    public String tochecktooyedit() {
        return PREFIX + "/checktooyedit.html";
    }

    /**
     * to调整运输单 明细
     */
    @RequestMapping("/tochecktooytiaozhengd")
    public String tochecktooytiaozhengd() {
        return PREFIX + "/checktooytiaozhengd.html";
    }

    /**
     * 查询运输单 明细
     */
    @ResponseBody
    @RequestMapping("/listOrder2")
    public LayuiPageInfo listOrder2(TransportDispatchParam transportDispatchParam) {
        User user = userService.getcurrentUser();
        transportDispatchParam.setDeptId(user.getDeptId());
        List<TransportDispatchResult> list = this.transportDispatchService.findgoodslistBySpecWeb(transportDispatchParam, null, user.getOperateId());
        LayuiPageInfo layuiPageInfo = new LayuiPageInfo();
        layuiPageInfo.setData(list);
        layuiPageInfo.setCount(list.size());
        return layuiPageInfo;
    }

    /**
     * 移除 派车单商品
     */
    @RequestMapping("/removeGoodsDispatch")
    @ResponseBody
    public ResponseData removeGoodsDispatch(TransportDispatchParam transportDispatchParam) {
        ResponseData data = new ResponseData();
        User user = userService.getcurrentUser();
        return this.transportDispatchService.removeGoodsDispatch(transportDispatchParam, data, user);
    }

    /**
     * 修改 派车单商品
     */
    @RequestMapping("/editGoodsDispatch")
    @ResponseBody
    public ResponseData editGoodsDispatch(TransportDispatchParam transportDispatchParam) {
        ResponseData data = new ResponseData();
        User user = userService.getcurrentUser();
        return this.transportDispatchService.editGoodsDispatch(transportDispatchParam, data, user);
    }

    /**
     * 调整 派车单商品
     */
    @RequestMapping("/tiaozhengGoodsDispatch")
    @ResponseBody
    @Permission
    public ResponseData tiaozhengGoodsDispatch(TransportDispatchParam transportDispatchParam) {
        ResponseData data = new ResponseData();
        User user = userService.getcurrentUser();
        return this.transportDispatchService.tiaozhengGoodsDispatch(transportDispatchParam, data, user);
    }

    /**
     * to查询运输单 明细
     */
    @RequestMapping("/tochecktooy")
    public String tochecktooy() {
        return PREFIX + "/checktooy.html";
    }

    /**
     * 定价审核
     * 驳回
     */
    @RequestMapping("/bohui")
    @ResponseBody
    public ResponseData bohui(TDispatchParam tDispatchParam) {
        User user = userService.getcurrentUser();
        tDispatchParam.setDeptId(user.getDeptId());
        TDispatchResult dispatchResult = tDispatchService.findBySpec(tDispatchParam, user.getOperateId());
        tDispatchParam.setId(dispatchResult.getId());
        tDispatchParam.setTstate("REJECTED");
        tDispatchParam.setExamineName(user.getName());
        tDispatchParam.setExamineTimes(DateUtil.getDateS());
        tDispatchService.update(tDispatchParam);
        return ResponseData.success();
    }

    /**
     * 定价审核
     * 通过
     */
    @RequestMapping("/tongguo")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public ResponseData tongguo(String[] strings) {
        User user = userService.getcurrentUser();
        String message = "";
        for (String dispatchNumber : strings) {
            TDispatchParam tDispatchParam = new TDispatchParam();
            tDispatchParam.setDispatchNumber(dispatchNumber);
            tDispatchParam.setDeptId(user.getDeptId());
            TDispatchResult dispatchResult = tDispatchService.findBySpec(tDispatchParam, user.getOperateId());
            BasicOperate basicOperate = basicOperateService.getById(dispatchResult.getOperateId());
            BigDecimal money = new BigDecimal(dispatchResult.getFreightMoney());
            if (ToolUtil.isNotEmpty(dispatchResult.getXiechefei())) {
                BigDecimal xiechefei = new BigDecimal(dispatchResult.getXiechefei());
                money = money.add(xiechefei).setScale(3, BigDecimal.ROUND_HALF_UP);
            }

            tDispatchParam.setId(dispatchResult.getId());
            tDispatchParam.setMoney(money.toString());
            tDispatchParam.setExamineName(user.getName());
            tDispatchParam.setExamineTimes(DateUtil.getDateS());

            TDispatchParam param = new TDispatchParam();
            param.setDeptId(user.getDeptId());
            param.setDeliverId(user.getDeliverId());
            param.setFulllv(dispatchResult.getStartDate());
            Integer trainNumber = tDispatchService.countCarnumber(param, user.getOperateId());//查询今日发运车次
            if (trainNumber == null) {
                tDispatchParam.setTrainNumber("1");
            } else {
                tDispatchParam.setTrainNumber((trainNumber + 1) + "");
            }
            tDispatchParam.setPaiType("web");

            TransportMsgParam dcqd = new TransportMsgParam();
            dcqd.setV3(dispatchResult.getCarId() + "");
            dcqd.setDeptId(user.getDeptId());
            dcqd.setStatus("Check-in at Warehouse");
            TransportMsgResult msgResult = transportMsgService.findDcqdBySpec(dcqd, user.getOperateId());
            if (msgResult != null) {
                TransportMsgParam transportMsgParam = new TransportMsgParam();
                transportMsgParam.setDispatchNumber(dispatchResult.getDispatchNumber());
                transportMsgParam.setStatus("Warehouse Loading");
                transportMsgParam.setMsgType("Driver");
                transportMsgParam.setContent(dispatchResult.getCarnumber() + "Arrived at the warehouse and started loading。" + "Current Location：" + msgResult.getContent());
                transportMsgParam.setTimes(msgResult.getTimes());
                transportMsgParam.setCreateUsername(msgResult.getCreateUsername());
                transportMsgParam.setDeliverId(user.getDeliverId());
                transportMsgParam.setDeptId(user.getDeptId());
                transportMsgParam.setSfyz("Yes");
                transportMsgParam.setNickName(msgResult.getNickName());
                transportMsgParam.setOpenId(msgResult.getOpenId());
                transportMsgService.add(transportMsgParam);

                tDispatchParam.setTstate("PENDING_DISPATCH");
                tDispatchService.update(tDispatchParam);
            } else {
                if (ToolUtil.isNotEmpty(basicOperate.getQdDriver()) && basicOperate.getQdDriver().equals("Yes")) {
                    message += "Detected" + dispatchResult.getSiji() + "No check-in record! Please complete warehouse check-in first on your next arrival.";
                    TransportMsgParam transportMsgParam = new TransportMsgParam();
                    transportMsgParam.setStatus("Check-in at Warehouse");
                    transportMsgParam.setMsgType("System");
                    transportMsgParam.setTimes(dispatchResult.getStartDate());
                    transportMsgParam.setV1(dispatchResult.getCarnumber());
                    transportMsgParam.setV2(dispatchResult.getSijidianhua());
                    transportMsgParam.setV3(dispatchResult.getCarId() + "");
                    transportMsgParam.setCreateUsername(dispatchResult.getSiji() + ",System Automatic Check-in");
                    transportMsgParam.setDeptId(user.getDeptId());
                    transportMsgParam.setDeliverId(user.getDeliverId());
                    transportMsgService.add(transportMsgParam);

                    TransportMsgParam transportMsgParam2 = new TransportMsgParam();
                    transportMsgParam2.setDispatchNumber(dispatchResult.getDispatchNumber());
                    transportMsgParam2.setStatus("Warehouse Loading");
                    transportMsgParam2.setMsgType("System");
                    transportMsgParam2.setContent(dispatchResult.getCarnumber() + "Arrived at the warehouse and started loading。");
                    transportMsgParam2.setTimes(dispatchResult.getStartDate());
                    transportMsgParam2.setCreateUsername(user.getName());
                    transportMsgParam2.setDeliverId(user.getDeliverId());
                    transportMsgParam2.setDeptId(user.getDeptId());
                    transportMsgService.add(transportMsgParam2);

                    tDispatchParam.setTstate("PENDING_DISPATCH");
                    tDispatchService.update(tDispatchParam);
                } else {
                    tDispatchParam.setTstate("PRICED");
                    tDispatchService.update(tDispatchParam);
                }
            }
        }
        ResponseData data = new ResponseData();
        data.setSuccess(true);
        data.setMessage(message);
        return data;
    }

    /**
     * to驳回 页面
     */
    @RequestMapping("/edit_examine")
    public String edit_examine() {
        return PREFIX + "/edit_examine.html";
    }

    /**
     * 通过id查询
     */
    @ResponseBody
    @RequestMapping("/getByid")
    public ResponseData getByid(Integer id) {
        return ResponseData.success(basicAddressService.getById(id));
    }

    /**
     * 查询 发货单位 、收货单位
     */
    @ResponseBody
    @RequestMapping("/findLocation")
    public ResponseData findLocation(OrderTransportParam orderTransportParam, String dispatchNumber) {
        User user = userService.getcurrentUser();
        orderTransportParam.setDeptId(user.getDeptId());
        List<OrderTransportResult> list = this.orderTransportService.findListBySpecNewNewNew(orderTransportParam, dispatchNumber, user.getOperateId());
        return ResponseData.success(list);
    }

    @Autowired
    private RoleService roleService;

    @Autowired
    private BasicCarrierService basicCarrierService;

    @Autowired
    private BasicDriverService basicDriverService;

    /**
     * 通过承运类型
     * 查询结算信息
     */
    @ResponseBody
    @RequestMapping("/getsettlement")
    public ResponseData getsettlement(TDispatchParam tDispatchParam) {
        if (tDispatchParam.getChengyunleixing().equals("Driver")) {
            return ResponseData.success(basicDriverService.getById(tDispatchParam.getCarId()));
        } else if (tDispatchParam.getChengyunleixing().equals("Carrier")) {
            return ResponseData.success(basicCarrierService.getById(tDispatchParam.getCarrierId()));
        }
        return ResponseData.success();
    }

    /**
     * 回单接口
     */
    @RequestMapping("/huidan")
    @ResponseBody
    public ResponseData huidan(TDispatchParam tDispatchParam) {
        tDispatchParam.setReturnTstate("POD_RECEIVED");
        tDispatchParam.setReturnTime(DateUtil.getDateS());
        this.tDispatchService.update(tDispatchParam);
        return ResponseData.success();
    }


    /**
     * 回单异常接口
     */
    @RequestMapping("/hdyichang")
    @ResponseBody
    public ResponseData hdyichang(TDispatchParam tDispatchParam) {
        tDispatchParam.setReturnTstate("Pending Exception");
        this.tDispatchService.update(tDispatchParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     */
    @RequestMapping("/edititem")
    @ResponseBody
    public ResponseData edititem(TDispatchParam tDispatchParam) {
        this.tDispatchService.update(tDispatchParam);
        return ResponseData.success();
    }

    /**
     * 修改备货口
     */
    @RequestMapping("/editStockPort")
    @ResponseBody
    public ResponseData editStockPort(OrderTransportParam orderTransportParam) {
        orderTransportService.update(orderTransportParam);
        return ResponseData.success();
    }

    /**
     * 上传装载照片 页面
     */
    @RequestMapping("/edit_zhuangzaifile")
    public String edit_zhuangzaifile() {
        return PREFIX + "/zhuangzaifile.html";
    }

    /**
     * 修改装载照片文件id
     */
    @RequestMapping("/editzhuangzaifile")
    @ResponseBody
    public ResponseData editzhuangzaifile(String fileId, String dispatchNumber) {
        if (ToolUtil.isEmpty(fileId)) {
            return ResponseData.error("Please upload the file！");
        }
        UpdateWrapper<TDispatch> updateWrapper = new UpdateWrapper<TDispatch>();
        updateWrapper.set("zhuangzai_fileid", fileId);
        updateWrapper.eq("dispatch_number", dispatchNumber);
        tDispatchService.update(updateWrapper);
        return ResponseData.success();
    }

    @Autowired
    private FileInfoService fileInfoService;

    /**
     * layui上传组件 通用文件上传接口
     *
     * @author fengshuonan
     * @Date 2019-2-23 10:48:29
     */
    @RequestMapping(method = RequestMethod.POST, path = "/upload")
    @ResponseBody
    public ResponseData layuiUpload(@RequestPart("file") MultipartFile file) {

        String fileId = this.fileInfoService.uploadFileTms(file);

        HashMap<String, Object> map = new HashMap<>();
        map.put("fileId", fileId);

        return ResponseData.success(0, "Upload successful", map);
    }
}


